package com.kzd.gtboon.manage

import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import java.io.File

private const val DISK_CACHE_DIR_NAME_APK = "Apk"

/**
 * 保存下载的apk
 */
fun getDiskCacheDirectoryApk(context: Context): File {
    val file = File(
        getDiskCacheDirectory(context),
        DISK_CACHE_DIR_NAME_APK
    )
    if (!file.exists()) {
        file.mkdirs()
    }
    return file
}

/**
 * 获取全部下载apk
 * */


@SuppressLint("SdCardPath")
fun getDiskCacheDirectory(context: Context): File {
    var cacheDir: File? = null
    if (Environment.MEDIA_MOUNTED == getExternalStorageState()) {
        cacheDir = getExternalCacheDir(context)
    }
    if (cacheDir == null) {
        cacheDir = context.cacheDir
    }
    if (cacheDir == null) {
        val cacheDirPath = "/data/data/${context.packageName}/cache/"
        cacheDir = File(cacheDirPath)
    }
    return cacheDir
}

private fun getExternalStorageState(): String {
    return try {
        Environment.getExternalStorageState()
    } catch (e: NullPointerException) {
        ""
    }
}

private fun getExternalCacheDir(context: Context): File? {
    val cacheDir = context.getExternalFilesDir("Cache")
    val exists = cacheDir?.exists() ?: return null
    if (!exists) {
        if (!cacheDir.mkdirs()) {
            return null
        }
    }
    return cacheDir
}